package web;

import com.alibaba.fastjson2.JSONObject;
import service.AdminUserService;
import service.impl.AdminUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;

/**
 * @author 于金鹏
 * @Date 2024/12/20 9:39
 * @Package StudentCheckSystem
 *
 * 后台用户登录
 */
@WebServlet("/userlogin")
public class UserLoginServlet extends HttpServlet {
    private AdminUserService adminUserService = new AdminUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            if (adminUserService.login(username, password)) {
                Cookie cookie = new Cookie("name","123");
                cookie.setPath("/");
                resp.addCookie(cookie);
                HttpSession session = req.getSession();
                session.setAttribute("loginTime", new Date());
                writer.write("{\"code\":200,\"msg\":\"登录成功\"}");
            } else {
                writer.write("{\"code\":500,\"msg\":\"用户名或密码错误\"}");
            }
        } catch (SQLException e) {
            writer.write(JSONObject.toJSONString("数据库查询出现错误：" + e.getMessage()));
            e.printStackTrace();
        }
        writer.flush();
        writer.close();
    }
}
